﻿namespace EyeSoft.Wpf.Facilities
{
	using System.ComponentModel;
	using System.Reflection;

	using EyeSoft.Reflection;
	using EyeSoft.Wpf.Facilities.Collections.ObjectModel;

	internal class SmartObservableCollectionInitializer
	{
		public static SmartObservableCollection<TCollectionType> Initialize<TCollectionType>(
			INotifyPropertyChanged instance,
			MemberInfo memberInfo)
		{
			if (memberInfo == null)
			{
				return new SmartObservableCollection<TCollectionType>();
			}

			var assignedCollection = memberInfo.GetValue(instance);

			SmartObservableCollection<TCollectionType> localCollection;

			if (assignedCollection != null)
			{
				localCollection = (SmartObservableCollection<TCollectionType>)assignedCollection;
				localCollection.Clear();
			}
			else
			{
				localCollection = new SmartObservableCollection<TCollectionType>();
				memberInfo.SetValue(instance, localCollection);
			}

			return localCollection;
		}
	}
}